package camid.util.dataanalysis;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JMeterTimestampAnalyser 
{
	
	private JMeterMetricSet metricSet;
	
	private Long experimentTime;
	
	private static final Long INTERVAL = 10000L;

	private List<Double> responseTimePerInterval;
	
	private List<Double> throughputPerInterval;
	
	public JMeterTimestampAnalyser(JMeterMetricSet metricSet) {
		super();
		this.metricSet = metricSet;
		
		responseTimePerInterval = new ArrayList<Double> ();
		throughputPerInterval = new ArrayList<Double> ();
	}
	
	public void analyse()
	{
		Iterator<JMeterMetric> metricIterator = metricSet.getSet().iterator();
		int successCounter = 0;
//		int lineCounter = 1;
		long startIntervalTimestamp = 0;
		Long cummulatedResponseTime = 0L;
		long endIntervalTimestamp = 0;
		
		if(metricIterator.hasNext())
		{
			JMeterMetric metric = metricIterator.next();
			long currentTimestamp = metric.getTimestamp();
			startIntervalTimestamp = currentTimestamp;
			endIntervalTimestamp = startIntervalTimestamp + INTERVAL;
		}
		
		while(metricIterator.hasNext())
		{
			JMeterMetric metric = metricIterator.next();
			long currentTimestamp = metric.getTimestamp();
			
			if((currentTimestamp < endIntervalTimestamp) && metricIterator.hasNext())
			{
				if(metric.isSuccess())
				{
					cummulatedResponseTime += metric.getResponseTime();
					successCounter++;
				}
//				lineCounter++;
			}
			else
			{
				if(successCounter > 0)
				{
					double doubleCounter = (double) successCounter;
					double avgRt = cummulatedResponseTime.doubleValue() / doubleCounter;
					double throughput = doubleCounter / (INTERVAL / 1000); 
					responseTimePerInterval.add(avgRt);
					throughputPerInterval.add(throughput);
				}
				
				successCounter = 0;
//				lineCounter = 0;
				cummulatedResponseTime = metric.getResponseTime();
				if(metric.isSuccess())
				{
					successCounter++;
				}
				startIntervalTimestamp = endIntervalTimestamp;
				endIntervalTimestamp = startIntervalTimestamp + INTERVAL;
			}
			
		}
		
	}

	public List<Double> getResponseTimePerInterval() 
	{
		return responseTimePerInterval;
	}

	public List<Double> getThroughputPerInterval() {
		return throughputPerInterval;
	}
	
	public void toStream(OutputStream out)
	{
		PrintWriter writer = new PrintWriter(out,true);
		for(int i = 0; i < responseTimePerInterval.size(); i++)
		{
			Double rt = responseTimePerInterval.get(i);
			Double tp = throughputPerInterval.get(i);
			writer.printf("%d;%d;%f;%f\n",
					metricSet.getTg().getNumberOfObjects(), 
					metricSet.getTg().getDelay(),
					rt, tp);
		}
	}
	
}
